package services

import (
	global2 "longmen/server/config/global"
	"longmen/server/internal/services/nami/services"
	"longmen/server/pkg/common/sdk/tx"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/redis/cache"
	"sync"
	"time"
)

var mutex sync.Mutex

type LiveCallBack struct {
	LiveData  []*liveCallBackData //直播数据
	DealTime  int64               //处理时间 断流多长时间结束该直播
	CheckTime time.Duration       //检测时间
}

type liveCallBackData struct {
	streamId string
	time     int64
	anchorid int
}

var liveCallBackServer *LiveCallBack

func (s *LiveCallBack) setCallBackLiveData(streamId string, anchorid int) {
	s.updateLiveStatus(anchorid, cache.PauseLive)
	return
	mutex.Lock()
	defer mutex.Unlock()
	for _, v := range s.LiveData {
		if v.streamId == streamId {
			return
		}
	}
	s.LiveData = append(s.LiveData, &liveCallBackData{streamId: streamId, time: time.Now().Unix(), anchorid: anchorid})
	s.updateLiveStatus(anchorid, cache.PauseLive)

}

func (s *LiveCallBack) delStreamId(streamId string) {
	var newLiveData []*liveCallBackData
	for _, l := range s.LiveData {
		if streamId != l.streamId {
			newLiveData = append(newLiveData, l)
		}
	}
	s.LiveData = newLiveData
}

func (s *LiveCallBack) updateLiveStatus(anchorid int, status cache.RoomStatus) bool {
	live, _ := cache.GetAnchorLive(anchorid)
	err := db_live.UpdateLiveStatus(global2.Live(), live.Liveid, int(status))
	if err != nil {
		global2.Log.Errorf("setCallBackLiveData err:%v", err)
		return false
	}
	live.Status = status
	cache.SetAnchorLive(anchorid, live)
	return true
}

func (s *LiveCallBack) doCheck() {
	ticker := time.NewTicker(s.CheckTime)
	for {
		tm := time.Now().Unix()
		<-ticker.C
		//global2.Log.Debugf("待停播数据长度:%d", len(s.LiveData))
		for _, v := range s.LiveData {
			q := &tx.QcloudSTS{}
			isOnline, err := q.GetOnLiveLive(v.streamId)
			if err != nil {
				global2.Log.Errorf("获取流状态失败:%v", err)
			}
			global2.Log.Debugf("待停播数据:%+v,流状态:%v", v, isOnline)
			if isOnline {
				if s.updateLiveStatus(v.anchorid, cache.StartLive) {
					s.delStreamId(v.streamId)
				}
				continue
			}

			if tm-v.time >= s.DealTime {
				// 5分钟轮询最终状态还是检测到不在线 走结束流程
				err = services.EndLive(v.anchorid)
				if err != nil {
					global2.Log.Errorf("延迟结束直播失败:%v", err)
					continue
				}
				s.delStreamId(v.streamId)
			}
		}
	}
}

func (s *Service) InitLiveCallBackServer() {
	liveCallBackServer = &LiveCallBack{
		DealTime:  300,
		CheckTime: time.Second * 10,
	}
	go liveCallBackServer.doCheck()
}

func (s *Service) SetCallBackLiveData(streamId string, anchorid int) {
	liveCallBackServer.setCallBackLiveData(streamId, anchorid)
}

func (s *Service) DelCallBackLiveData(streamId string) {
	liveCallBackServer.delStreamId(streamId)
}
